package com.runachina.othercompany;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.runachina.R;
import com.runachina.common.BaseActivity;
import com.runachina.common.CompanyActivity;
import com.runachina.java.SendDataAnalysis;
import com.runachina.java.TcpSocket;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 读取欧标的表
 */



public class EuropeCompanyActivity extends BaseActivity {

    private EditText inputnum;
    private Button btnread;
    private TextView sendtext;
    public  static TextView rcvtext,rcvbyte;

    private static String ifNumOver="over?yes";

    private static String sendMsg="";

    //兰吉尔、伟岸 释放
    private static byte[] Release={0x10,0x40,(byte)0xFD,0x3D,0x16,0x00,0x16};
    //兰吉尔、伟岸 读取
    private static byte[] reading={0x10,(byte)0x7B,(byte)0xFD,0x78,0x16,0x00,0x16};

    //兰吉尔、伟岸 准备读取 680b0b 6853fd52 91616266 ffffffff 5816
    private static byte [] readyRead= {(byte)0xFE,(byte)0xFE,(byte)0xFE,0x68,0x0B,0x0B,0x68,0x53,(byte) 0xFD,0x52,
            0x00,0x00,0x00,0x00,//地址顺序
            (byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,
            (byte) 0x00,0x16,//校验和从0x53开始
            (byte) 0x00,0x16};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_readeurope);

        set_toolbar(companyName + "/" + readMethod, "");

        set_leftmenu(EuropeCompanyActivity.this,EuropeCompanyActivity.class);

        init_view();

        inWhichAc="othercompany.EuropeCompanyActivity";
    }


    /**
     * 初始化界面控件
     */
    void init_view(){
        inputnum=(EditText)findViewById(R.id.inputnum);
        btnread=(Button)findViewById(R.id.btnread);
        btnread.setOnClickListener(readMeter);

        sendtext=(TextView)findViewById(R.id.sendtext);
        rcvtext =(TextView)findViewById(R.id.rcvtext);
        rcvbyte =(TextView)findViewById(R.id.rcvbyte);
    }
    private void clear_textDisplay(){
        sendtext.setText("");
        rcvtext.setText("");
        rcvbyte.setText("");
    }

    /**
     * 按键响应事件：点击读取抄表
     * 显示发送出去的数据
     */
    OnClickListener readMeter = new OnClickListener() {
        @Override
        public void onClick(View v) {
            clear_textDisplay();
            //获取完整的发送sendbyte[]
            String meterNum=inputnum.getText().toString();

            if(meterNum.length()>=8){
                startTimer(TI);
                releaseMeter();
                readyReadMeter();
                readingMeter();
            }else{
                show("表号错误!");
            }
        }
    };

    /**
     * 欧标的表：首先需要释放
     */
    void releaseMeter(){
        byte[] sendbyte=SendDataAnalysis.contactTransmit(Release);
        String sendResult= TcpSocket.wifiSendByte(sendbyte);
//        new Timer().schedule(new TimerTask() {
//            @Override
//            public void run() {
//                TcpSocket.receServerMessage();
//            }
//        },3000);
        //显示发送报文
        sendMsg="释放:"+byteToHexString(sendbyte);
        sendtext.setText(sendMsg);
        sleep(1000);
    }
    /**
     * 欧标的表: 准备读表
     */
    void readyReadMeter(){

        String meterNum=inputnum.getText().toString();
        byte[] sendbyte=SendDataAnalysis.europeRead(readyRead, meterNum, ifNumOver, 10, 13);
        String sendResult= TcpSocket.wifiSendByte(sendbyte);
        //显示发送报文
        sendMsg=sendMsg+"\n准备:"+byteToHexString(sendbyte);
        sendtext.setText(sendMsg);
        sleep(1000);
    }
    /**
     * 欧标的表: 读表
     */
    void readingMeter(){

        byte[] sendbyte=SendDataAnalysis.contactTransmit(reading);
        String sendResult = TcpSocket.wifiSendByte(sendbyte);
        //显示发送报文
        sendMsg=sendMsg+"\n读取:"+byteToHexString(sendbyte);
        sendtext.setText(sendMsg);
        sleep(1000);
    }


    /**
     * Toolbar中的Menu菜单项
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /**
     * Activity创建时候会执行一次，所以可以用来初始化toolbar中的wifi图标
     * @return
     */
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        MenuItem menuItem = menu.findItem(R.id.menu_connect);
        //wifi connect，返回当前连接状态
        String connectResult= TcpSocket.readConnect();
        if((connectResult.equals("连接成功!"))||connectResult.equals("已经连接!")){
            menuItem.setTitle("connect!");
            menuItem.setIcon(R.drawable.wifi_connect);
        }else{
            menuItem.setTitle("no connect!");
            menuItem.setIcon(R.drawable.wifi_noconnect);
        }
        return true;
    }
    private MenuItem me;
    private int type=0;
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        me=item;
        System.out.println("onOptionsItemSelected");

        switch (item.getItemId()){
            case R.id.menu_connect:
                String connectResult= TcpSocket.wificonnect();//wifi connect
                show(connectResult);//TOast connect result
                if((connectResult.equals("连接成功!"))||connectResult.equals("已经连接!")){
                    item.setTitle("connect!");
                    item.setIcon(R.drawable.wifi_connect);
                }else{
                    item.setTitle("no connect!");
                    item.setIcon(R.drawable.wifi_noconnect);
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            goWifiSetting();
                            type=1;
                        }
                    },1000);
                }
                return true;
            case R.id.menu_choice:
                intent = new Intent(EuropeCompanyActivity.this, CompanyActivity.class);
                startActivity(intent);
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    //每次进来判断是否是从设置wifi页面进来的，如果是，重新连接socket，判断是否可用
    @Override
    protected void onResume() {
        super.onResume();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                type=0;
                String connectResult = TcpSocket.wificonnect();//wifi connect
                //show(connectResult);//TOast connect result
                if (isWifi()) {
                    if (me != null) {
                        if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {

                            me.setTitle("connect!");
                            me.setIcon(R.drawable.wifi_connect);
                        } else {

                            me.setTitle("no connect!");
                            me.setIcon(R.drawable.wifi_noconnect);
                        }
                    }
                } else {
                    if (me!=null){
                        me.setTitle("no connect!");
                        me.setIcon(R.drawable.wifi_noconnect);
                    }

                }
            }
        });
    }

    /**
     * 设置back监听
     */
    @Override
    public void onBackPressed() {
        exitApp();
    }
}
